package com.biz.primus.management.commodity.controller;

import com.biz.primus.commodity.vo.CategoryQueryVo;
import com.biz.primus.commodity.vo.backend.CategoryListItemVo;
import com.biz.primus.commodity.vo.backend.UpdateCategoryVo;
import com.biz.primus.common.vo.SpringPageVO;
import com.biz.primus.management.base.controller.AbstractBaseController;
import com.biz.primus.management.commodity.feign.CategoryFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

/**
 * @author jiangnan
 * @Description: TODO
 * @create 2017-10-12-下午2:19
 */
@Controller
@RequestMapping("management/category")
public class CategoryController extends AbstractBaseController {

    private final CategoryFeignClient categoryFeignClient;

    @Autowired
    public CategoryController(CategoryFeignClient categoryFeignClient) {
        this.categoryFeignClient = categoryFeignClient;
    }


    @GetMapping(value = "list")
    @ResponseBody
    @PreAuthorize("hasAuthority('OPT_CATEGORY_LIST')")
    public ModelAndView list(@ModelAttribute("reqVo") CategoryQueryVo reqVo) {
        SpringPageVO<CategoryListItemVo> categoryPage = categoryFeignClient.findAll(reqVo);
        SpringPageVO<CategoryListItemVo> categories = categoryFeignClient.findAll(new CategoryQueryVo());
        return new ModelAndView("category/list", "pages", categoryPage).addObject("categories",categories);
    }

    @RequestMapping("{id}")
    @PreAuthorize("hasAuthority('OPT_CATEGORY_DETAIL')")
    public ModelAndView edit(@PathVariable Long id) {
        return new ModelAndView("category/detail")
                .addObject("category", categoryFeignClient.getCategoryById(id));
    }


    @PostMapping("save")
    @PreAuthorize("hasAuthority('OPT_CATEGORY_UPDATE')")
    public ModelAndView save(@Valid UpdateCategoryVo categoryVo, BindingResult result) {
        error(result);
        categoryFeignClient.update(categoryVo);
        return new ModelAndView("redirect:/management/category/list");
    }






}
